#include <string.h>
#include <unistd.h>
#include <errno.h>

#include "File.h"

jint Java_my_common_File_read0(JNIEnv* env, jclass clazz, jint fd, jobject jbuf, jint pos, jint limit) {
	ssize_t res;
	void* buf;
	int err;

	buf = (*env)->GetDirectBufferAddress(env, jbuf);
	do {
		res = read(fd, buf + pos, (size_t) (limit - pos));
	} while (res == -1 && ((err = errno) == EINTR));

	if (res < 0) {
		return -err;
	}
	return (jint) res;
}

jint Java_my_common_File_write0(JNIEnv* env, jclass clazz, jint fd, jobject jbuf, jint pos, jint limit) {
	ssize_t res;
	void* buf;
	int err;

	buf = (*env)->GetDirectBufferAddress(env, jbuf);
	do {
		res = write(fd, buf + pos, (size_t) (limit - pos));
	} while (res == -1 && ((err = errno) == EINTR));

	if (res < 0) {
		return -err;
	}
	return (jint) res;
}

jint Java_my_common_File_close0(JNIEnv* env, jclass clazz, jint fd) {
	if (close(fd) < 0) {
		if (errno != EINTR) {
			return -errno;
		}
	}
	return 0;
}
